package com.gper.edu.vip.builder.singleton;

import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author: ellis.guan
 * @Description: 容器式单例
 * @Date: 2020/2/26 22:04
 * @Version: 1.0
 */
public class ContainerSingleton {

    private ContainerSingleton(){}

    private static final ConcurrentHashMap<String,Object> ioc = new ConcurrentHashMap<String, Object>();

    private static void putInstance(String className,Object value){
        synchronized (ioc) {
            if (!ioc.containsKey(className)) {
                ioc.put(className, value);
            }
        }
    }

    public static Object getInstance(String className){
        if (ioc.containsKey(className)){
            return ioc.get(className);
        }else {
            try {
                Class clazz = Class.forName(className);
                Object instance = clazz.newInstance();
                putInstance(className,instance);
            }catch (Exception e){
                e.printStackTrace();
            }
            return ioc.get(className);
        }
    }
}
